#! usr/bin/python 
import time
import os

def mini():
    fw=open('min_protein_coding.gtf','w')
    fw.write('ch\tgene\tstart\tend\tdire')
    fgtf=open('gencode.v24.protein_coding.gtf')
    for lines in fgtf.readlines()[0:]:
        if lines.split('\t')[2]=='gene':
            fw.write(lines.split('\t')[0]+'\t'+lines.split('\t')[3]+'\t'+lines.split('\t')[4]+'\t'+lines.split('\t')[6]+'\t'+lines.split('\t')[8].split('"')[7]+'\n')
    fw.close()

#sortBed -i  noncoding.bed > noncoding_sort.bed
#sortBed -i  min_protein_coding.gtf > min_protein_coding_sort.gtf

def overlap():
    fcod=open('min_protein_coding_sort.gtf')
    fcod_read=fcod.read()
    fcod_split=fcod_read.split('\n')
    foverlap2=open('allsense.bed','w')
    foverlap=open('overlap_res.txt','w')
    flnc=open('noncoding_sort.bed')
    s=0
    k=0
    for lnc in flnc.readlines()[0:]:
        k=k+1
        print (k)
        lnc_start=int(lnc.split('\t')[1])
        lnc_end=int(lnc.split('\t')[2])
        lnc_dire=lnc.split('\t')[-1].strip('\n')
        for i in range(s,19813): 
            two_line=fcod_split[i:i+2]
            if lnc.split('\t')[0]==two_line[0].split('\t')[0]: #the first 
                last_start=int(two_line[0].split('\t')[1])
                last_end=int(two_line[0].split('\t')[2])
                next_start=int(two_line[1].split('\t')[1])
                next_end=int(two_line[1].split('\t')[2])
                dire_left=two_line[0].split('\t')[3]
                dire_right=two_line[1].split('\t')[3]
                if (lnc_start > last_end) and (lnc_end < next_start): #no overlap (bidirectioanal or intergenic)
                    s=i
                    dis_left=lnc_start - last_end
                    dis_right=next_start - lnc_end
                    min_dis=min(dis_left,dis_right)
                    if min_dis < 1000: 
                        if min_dis == dis_left:
                            if not lnc_dire == dire_left: #directioanl is 
                                foverlap.write('Bidirectional\t'+lnc.strip('\n')+'\t'+two_line[0].strip('\n')+'\t'+two_line[1]+'\n')
                            else:
                                foverlap.write('Intergenic\t'+lnc.strip('\n')+'\t'+two_line[0].strip('\n')+'\t'+two_line[1]+'\n')
                        if min_dis == dis_right:
                            if not lnc_dire == dire_right:
                                foverlap.write('Bidirectional\t'+lnc.strip('\n')+'\t'+two_line[0].strip('\n')+'\t'+two_line[1]+'\n')
                            else:
                                foverlap.write('Intergenic\t'+lnc.strip('\n')+'\t'+two_line[0].strip('\n')+'\t'+two_line[1]+'\n')
                    else:
                        foverlap.write('Intergenic\t'+lnc.strip('\n')+'\t'+two_line[0].strip('\n')+'\t'+two_line[1]+'\n')
                    break

                else: #sense or antisense (judge direction)
                    if ((lnc_start < last_end) and (lnc_end > last_start)): #overlap with left
                        s=i
                        # print (lnc_dire,dire_left)
                        if lnc_dire == dire_left:
                            foverlap2.write(lnc.strip('\n')+'\t'+two_line[0]+'\n')
                            foverlap.write('sense\t'+lnc.strip('\n')+'\t'+two_line[0]+'\t'+two_line[1]+'\n')
                        else:
                            foverlap.write('antisense\t'+lnc.strip('\n')+'\t'+two_line[0]+'\t'+two_line[1]+'\n')
                        break 
    fcod.close()
    foverlap.close()
    flnc.close()
    foverlap2.close()


def coding():
    fcoding=open('gencode.v24.protein_coding.gtf')
    fwcoding=open('gene_exon.bed','w')
    for cod in fcoding.readlines()[0:]:
        if cod.split('\t')[2]=='gene':
            chr_cod=(cod.split('\t')[0])
            gene_name=cod.split('\t')[8].split('"')[7]
        if cod.split('\t')[2]=='exon':
            fwcoding.write(chr_cod+'\t')
            fwcoding.write(cod.split('\t')[3]+'\t'+cod.split('\t')[4]+'\t')
            fwcoding.write(gene_name+'\n')
    fcoding.close()
    fwcoding.close()

#sortBed -i  gene_exon.bed > gene_exon_sort.bed
#sortBed -i  allsense.bed> allsense_sort.bed

def exon():
    m=0
    fwei=open('exonic.txt','w')
    fsense=open('allsense_sort.bed')
    f_exon=open('gene_exon_sort.bed')
    fexon_read=f_exon.read()
    fexon_split=fexon_read.split('\n')

    s=4250
    for line in fsense.readlines()[0:13076]:
        m=m+1
        print ('m: '+str(m))
        cod_gene=line.split('\t')[10].strip('\n')
        chr_cod=line.split('\t')[0]
  
        for j in range(s,1044648):
            exon_line=fexon_split[j]
            
            if exon_line.split('\t')[0]==chr_cod: #same chr 
                if exon_line.split('\t')[3]==cod_gene: #same gene
                    lnc_start=line.split('\t')[1]
                    lnc_end=line.split('\t')[2]
                    lnc_name1=line.split('\t')[3]
                    lnc_name2=line.split('\t')[4]

                    exon_start=exon_line.split('\t')[1]
                    exon_end=exon_line.split('\t')[2]

                    if (lnc_end>exon_start) and (lnc_start<exon_end):
                        fwei.write(lnc_name1+'\t'+lnc_name2+'\t'+'exon'+'\n')
                        break
                        print ('j: '+str(j))
                        s=j
                    else:
                        pass
                        print ('j: '+str(j))
                        s=j
    fwei.close()
    fsense.close()
    f_exon.close()

def tiqu():
    fei=open('exonic_intronic_antisense_Intergenic_Bidirectional.txt','w')
    all_exon=[]
    fexon=open('exonic.txt')
    for exon in fexon.readlines()[0:]:
        all_exon.append(exon.split('\t')[0])

    allsense=[]
    fallsense=open('allsense_sort.bed')
    for sense_gene in fallsense.readlines():
        allsense.append(sense_gene.split('\t')[3])

    for sense in allsense:
        if sense in all_exon:
            fei.write(sense+"\texonic\n")
        else:
            fei.write(sense+"\tintronic\n")

    fcr=open('overlap_res.txt')
    antisense=[]
    Intergenic=[]
    Bidirectional=[]
    for cr in fcr.readlines():
        if cr.split('\t')[0]=='antisense':
            antisense.append(cr.split('\t')[4])
        if cr.split('\t')[0]=='Intergenic':
            Intergenic.append(cr.split('\t')[4])
        if cr.split('\t')[0]=='Bidirectional':
            Bidirectional.append(cr.split('\t')[4])

    for anti in antisense:
        fei.write(anti+"\tantisense\n")
    for Inter in Intergenic:
        fei.write(Inter+"\tIntergenic\n")
    for Bid in Bidirectional:
        fei.write(Bid+"\tBidirectional\n")

    fei.close()


if __name__ == '__main__':
    start_time=time.clock()
    
    # mini()
    # os.system("sortBed -i  noncoding.bed > noncoding_sort.bed")
    # os.system("sortBed -i  min_protein_coding.gtf > min_protein_coding_sort.gtf")

    # overlap()

    # coding()
    # os.system("sortBed -i  gene_exon.bed > gene_exon_sort.bed")
    # os.system("sortBed -i  allsense.bed> allsense_sort.bed")

    #exon()

    tiqu()

    end_time=time.clock()
    time_used=end_time-start_time
    print(time_used)


